import asyncore
import asynchat
import socket

class ChatServer(asyncore.dispatcher):
    def __init__(self,list_num,host,post):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET,socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host,post))
        self.listen(list_num)
        print('房间已开')

    def handle_accept(self):
        conn,addr = self.accept()
        c_ip,c_port = addr
        ChatSession(self, conn, c_ip, c_port)


class ChatSession(asynchat.async_chat):
    clients = []
    def __init__(self, server, conn, addr, port):
        asynchat.async_chat.__init__(self, conn)
        self.server = server
        self.addr = addr
        self.port = port
        self.set_terminator(b'BAY')
        self.clients.append(self)
        self.user_name = "用户" + str(self.port)
        self.comming()

    def comming(self):
        data = self.user_name+"进入聊天室"
        print(data)
        self.broad(data)

    def collect_incoming_data(self, data):
        if len(data) != 0:
            data1 = str(self.user_name)+'说：'+data.decode('utf8')
            print(data1)
            self.broad(data1)

    def broad(self,data):
        for i in self.clients:
            try:
                i.push(data.encode('utf8'))
            except Exception:
                self.clients.remove(i)

    def found_terminator(self):
        data = "{} 离开了聊天室".format(self.user_name)
        print(data)
        self.broad(data)
        self.close_when_done()
        try:
            self.clients.remove(self)
        except Exception:
            pass

if __name__ == '__main__':
    s = ChatServer(10,'127.0.0.1',18888)
    asyncore.loop()